//app.js
App({
  globalData: {
    userInfo: null,
    sysinfo: null,
    // baseUrl: 'https://47.98.115.10'
  },
  onLaunch: function () {
    // 展示本地存储能力
    this.globalData.sysinfo = wx.getSystemInfoSync()
    console.log(this.globalData.sysinfo)
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log('res', res.code);
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
    if(wx.cloud){
      wx.cloud.init({
        //环境ID
        env: 'jewellery-bbbf61',
        //获取调用api者的信息
        traceUser: true,
      })
    }
  },
  userInfoReadyCallback: function(res){
    console.log('用户信息', res.userInfo);
  },
  getModel: function () { //获取手机型号
    return this.globalData.sysinfo["model"]
  },
  getVersion: function () { //获取微信版本号
    return this.globalData.sysinfo["version"]
  },
  getSystem: function () { //获取操作系统版本
    return this.globalData.sysinfo["system"]
  },
  getPlatform: function () { //获取客户端平台
    return this.globalData.sysinfo["platform"]
  },
  getSDKVersion: function () { //获取客户端基础库版本
    return this.globalData.sysinfo["SDKVersion"]
  },
  // 数据监听
  setWatcher(data, watch) {
    Object.keys(watch).forEach(v => {
      let key = v.split('.');
      let nowData = data;
      for (let i = 0; i < key.length - 1; i++) {
          nowData = nowData[key[i]];
      }
      let lastKey = key[key.length-1];
      this.observe(nowData, lastKey,watch[v]);
    })
  },
  observe(obj, key,watchFun) {
    var val = obj[key];
    Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: true,
      set: function(value) {
          val = value;
          watchFun(value,val);
      },
      get: function() {
          return val;
      }
    })
  },
  buf2hex: function (buffer) {
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('')
  },
  buf2string: function (buffer) {
    var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
    var str = ''
    for (var i = 0; i < arr.length; i++) {
      str += String.fromCharCode(arr[i])
    }
    return str
  },
})